<?php
namespace app\index\controller;

use app\common\controller\HomeBase;
use Firebase\JWT\JWT;
use org\SendMsg;
use org\SiteMap;
use TencentCloud\Captcha\V20190722\CaptchaClient;
use TencentCloud\Captcha\V20190722\Models\DescribeCaptchaResultRequest;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use think\facade\Cache;
use think\facade\Config;
use think\helper\Time;
use wechat\WechatAuth;
use app\common\model\User as UserModel;

class Index extends HomeBase
{
    public function index()
    {
        $this->assign('index_style',"index-style");

        $article_count = model("article")->where(['status' => 1])->count('id');
        $user_count = model("user")->where(['status' => 1])->count('id');

        $timeArr = Time::today();
        $day_num = model('article')->where('create_time','gt',$timeArr[0])->where('create_time','lt',$timeArr[1])->count();

        $this->site_seo("home");
        return $this->fetch('index',['day_num' => $day_num,'article_count' => $article_count,'user_count' => $user_count]);
    }

    /**
     * 文档下载
     */
    public function download()
    {
        $id = $this->request->param('id');

        if (!empty($this->user_info)) {

            //如果是免费版直接下载
            $item = model('article')->where(['id' => $id])->find();

            if (empty($item))
            {
                return $this->error("文件不存在");
            }

            //如果文档 或者 全站免费下载的话 直接下载
            if ($item['is_free'] == 1 || $this->siteConfig['pay_type_free'] == 1) {

                if ($item['storage_type'] == "baidu" || $item['storage_type'] == "189")
                {
                    $data = curl_url(sprintf("%s/fid/%s",$this->siteConfig['baidu_api'],$item['fid']));
                    $this->echoJson($data['data'],200,"获取成功");
                }else {
                    $data = curl_url($this->siteConfig['interface_url'] . "/get_sign_url",['file_name' => $item['file_name'],'bid' => $item['bid']]);
                    $data = json_decode($data['data'],true);
                    $this->echoJson($data['data'],200,"获取成功!");
                }

            }else {
                if($this->user_info['vip_id'] > 0) {

                    $vip = model('vip')->where(['id' => $this->user_info['vip_id']])->find();
                    $timeArr = Time::today();
                    $downNum = model('down_log')->where(['user_id' => $this->user_info['id']])->where('create_time','gt',$timeArr[0])->where('create_time','lt',$timeArr[1])->count();

                    if ($downNum > $vip['down_num'] ){
                        $this->echoJson('',-1,"下载次数超过".$vip['down_num']."次,请明日在下载!");
                    }else {

                        if ($item['storage_type'] == "baidu" || $item['storage_type'] == "189")
                        {
                            $data = curl_url(sprintf("%s/fid/%s",$this->siteConfig['baidu_api'],$item['fid']));
                            $this->echoJson($data['data'],200,"获取成功");

                        }else {

                            $data = curl_url($this->siteConfig['interface_url'] . "/get_sign_url",['file_name' => $item['file_name'],'bid' => $item['bid']]);
                            $data = json_decode($data['data'],true);

                            if (model('down_log')->where(['user_id' =>  $this->user_info['id']])->where(['doc_id' => $id])->count() == 0) {
                                model('down_log')->insert([
                                    'title' => $item['title'],
                                    'user_id' => $this->user_info['id'],
                                    'doc_id' => $id,
                                    'create_time' => time(),
                                ]);
                            }
                            $this->echoJson($data['data'],200,"获取成功!");
                        }
                    }

                }else {
                    $this->echoJson("",-1,"请先开通会员!");
                }
            }

        }else{
            $this->echoJson("",-1,"用户未登录");
        }
    }


    /**
     * 发送验证码
     */
    public function send_code ()
    {
        if ($this->request->isPost())
        {
            try {

                $ticket = $_POST["ticket"];
                $randstr = $_POST["randstr"];
                $phone = trim($this->request->param("phone"));

                $cred = new Credential($this->siteConfig['tencent_keyid'], $this->siteConfig['tencent_secretkey']);
                $httpProfile = new HttpProfile();
                $httpProfile->setEndpoint("captcha.tencentcloudapi.com");

                $clientProfile = new ClientProfile();
                $clientProfile->setHttpProfile($httpProfile);
                $client = new CaptchaClient($cred, "", $clientProfile);

                $req = new DescribeCaptchaResultRequest();

                $params = array(
                    "CaptchaType" => 9,
                    "Ticket" => $ticket,
                    "UserIp" => $this->request->ip(),
                    "Randstr" => $randstr,
                    "CaptchaAppId" => (int)$this->siteConfig['tencent_captcha_appid'],
                    "AppSecretKey" =>  $this->siteConfig['tencent_app_secretkey']
                );
                $req->fromJsonString(json_encode($params));

                $resp = json_decode($client->DescribeCaptchaResult($req)->toJsonString(),true);
                if ($resp['CaptchaCode'] == 1 && $resp['CaptchaMsg'] == "OK")
                {

                    $sendMsg = new SendMsg($this->siteConfig['sms_api_keyid'],$this->siteConfig['sms_api_secret'],$this->siteConfig['sms_api_appid'],$this->siteConfig['sms_api_sign'],$this->siteConfig['sms_api_template_id']);

                    if (check_mobile_number($phone))
                    {
                        if (!strpos($phone,"+86")) {

                            $code = rand(1000,9999);
                            Cache::set("verify_code_" . md5($this->request->ip()),$code,60 * 5);

                            $data = $sendMsg->tencent("+86" . $phone,[(string)$code,'5']);

                            $data = $data['SendStatusSet'][0];
                            if ($data['Code'] == 'Ok' && $data['Message'] == "send success")
                            {
                                return $this->echoJson([],200,"短信发送成功");
                            }else {
                                return $this->echoJson([],-1,"短信发送失败");
                            }
                        }

                    }else {
                        return $this->echoJson([],-1,"手机号不正确");
                    }

                }

            }
            catch(TencentCloudSDKException $e) {
                echo $e;
            }
        }

    }


    /**
     * 站点地图
     */
    public function sitemap ()
    {
        $full_list = model("article")->where(["status" => 1])->limit(20)->order('sort','desc')->select();
        $site = new Sitemap();

        foreach ($full_list as $item)
        {
            $url = \request()->domain(). "/zy-" . $item['id'] . '.html';
            $site->AddItem($url, 0,'daily',$item['create_time']);
        }

        $site->Show();
    }

    /**
     * vip付款页面
     * @return mixed
     */
    public function vip ()
    {
        $this->site_seo("home");
        return $this->fetch('vip');
    }

    /**
     * 加入平台
     * @return mixed
     */
    public function join_platform ()
    {
        $this->site_seo("home");
        return $this->fetch('join_platform');
    }


    /**
     * 检查微信登录
     */
    public function check_weixin_login()
    {
        $token = $this->request->param("token");
        if (!empty($token))
        {
            $key = "weixin_qrcode_login_" . $this->request->ip();
            $decoded = (array)JWT::decode($token, $key, array('HS256'));

            $login_uuid = Cache::get("weixin_qrcode_login_uuid_" . $decoded['login_uuid']);

            if ($decoded['login_uuid'] == $login_uuid)
            {
                $user_id = Cache::get('weixin_qr_login_id_' . $login_uuid);
                if (!empty($user_id)) {
                    UserModel::userIdLogin($user_id);
                    return $this->echoJson("",200,"登录成功");
                }else {
                    return $this->echoJson("",-1,"等待扫码");
                }

            }else {
                return $this->echoJson("",-1,"非法参数");
            }
        }
        return $this->echoJson("",-1,"参数错误");
    }


    /**
     * 获取登录二维码
     */
    public function get_login_qrcode()
    {
        $uuid = get_weixin_login_uuid();

        $key = "weixin_qrcode_login_" . $this->request->ip();

        $payload = array(
            "login_uuid" => $uuid
        );

        $wechat = new WechatAuth($this->siteConfig['weixin_appid'],$this->siteConfig['weixin_secret']);
        $qrcode = '';

        $resp = $wechat->qrcodeCreate($uuid,60 * 5);
        if (array_key_exists("ticket",$resp)) {
            $qrcode = $wechat->showQrCode($resp['ticket']);
        }

        $token = JWT::encode($payload, $key);

        return $this->echoJson([
            'token' => $token,
            'qrcode' => $qrcode,
        ]);
    }

}
